import 'dart:convert';

import 'package:encrypt/encrypt.dart';
import 'package:zhaoxiaowu_app/utils/rsa/rsa_data.dart';

class RSAUtils {
  /// 通过私钥解密
  static Future<String> decodeString(String content) async {
    dynamic privateKey = RSAKeyParser().parse(kPrivateKey);
    final encrypter = Encrypter(RSA(privateKey: privateKey));
    final encrypted = Encrypted.fromBase64(content);
    return encrypter.decrypt(encrypted);
  }

  /// 通过公钥加密
  /// content = 加密前的文本
  /// 长参数分段加密
  static Future<String> encodeString(String content) async {
    dynamic publicKey = RSAKeyParser().parse(kPublicKey);
    final encrypter = Encrypter(RSA(publicKey: publicKey));

    List<int> sourceBytes = utf8.encode(content);
    int inputLen = sourceBytes.length;
    int maxLen = 117;
    List<int> totalBytes = [];
    for (var i = 0; i < inputLen; i += maxLen) {
      int endLen = inputLen - i;
      List<int> item;
      if (endLen > maxLen) {
        item = sourceBytes.sublist(i, i + maxLen);
      } else {
        item = sourceBytes.sublist(i, i + endLen);
      }
      totalBytes.addAll(encrypter.encryptBytes(item).bytes);
    }
    return base64.encode(totalBytes);
  }
}
